﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace SlamCms.Common.Security
{
	public class AuthenticationService
	{
		private const string SlamPreviewMode = "SlamPreviewMode";
		private const string SlamAuthentication = "SlamAuthentication";
		private readonly HttpContextBase httpContext;

		public AuthenticationService(HttpContextBase httpContext)
		{
			this.httpContext = httpContext;
		}

		public void CreateOrUpdateSlamPreviewModeCookie()
		{
			if (httpContext.Request.Cookies[SlamPreviewMode] != null) return;

			var previewCookie = new HttpCookie(SlamPreviewMode, "true");
			httpContext.Response.AppendCookie(previewCookie);
		}

		public bool GetSlamPreviewMode()
		{
			return httpContext.Request.Cookies[SlamPreviewMode] != null;
		}

		public void RemoveSlamPreviewModeCookie()
		{
			var previewModeCookie = new HttpCookie(SlamPreviewMode, "false");
			previewModeCookie.Expires = DateTime.Now.AddDays(-1);
			httpContext.Response.AppendCookie(previewModeCookie);
		}

		#region Slam Authentication

		public void CreateOrUpdateSlamAuthenticationCookie()
		{
			var username = httpContext.User.Identity.Name.Contains("|") ? httpContext.User.Identity.Name.Split('|')[1] : HttpContext.Current.User.Identity.Name;
			CreateOrUpdateSlamAuthenticationCookie(username);
		}

		public void CreateOrUpdateSlamAuthenticationCookie(string username)
		{
			var slamAuthCookie = new HttpCookie(SlamAuthentication, EncryptionService.EncryptWithTimestamp(username));
			httpContext.Response.AppendCookie(slamAuthCookie);
		}

		public void RemoveSlamAuthenticationCookie()
		{
			var slamAuthCookie = new HttpCookie(SlamAuthentication, "");
			slamAuthCookie.Expires = DateTime.Now.AddDays(-1);
			httpContext.Response.AppendCookie(slamAuthCookie);
		}

		public string GetSlamUserName()
		{
			return GetSlamUserName(new TimeSpan(3, 0, 0));
		}

		public string GetSlamUserName(TimeSpan maximumValidAge)
		{
			var slamAuthCookie = httpContext.Request.Cookies[SlamAuthentication];
			if (slamAuthCookie != null)
			{
				var userName = EncryptionService.DecryptWithExpiration(slamAuthCookie.Value, maximumValidAge);
				if (userName.Length > 0)
					CreateOrUpdateSlamAuthenticationCookie(userName);
				return userName;
			}
			return "";
		}

		#endregion
	}
}
